<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: 当燃 2016-01-09
 */
namespace app\admin\controller;
use app\admin\logic\GoodsLogic;
use app\admin\logic\OrderLogic;
use think\AjaxPage;
use think\Page;
use think\Db;

header("Content-Type: text/html; charset=utf8");
class Station extends Base {
	
	/*
    * 初始化操作
    */
    public function _initialize()
    {
        parent::_initialize();
        if (session('?user')) {
            $user = session('user');
            $user = M('users')->where("user_id", $user['user_id'])->find();
            session('user', $user);  //覆盖session 中的 user
            $this->user = $user;
            $this->user_id = $user['user_id'];
            $this->assign('user', $user); //存储用户信息
        }
    }    

    public function index(){
    
        return $this->fetch();
    }
    
    /*
     * 品酒站列表
     * */
    public function stationList(){
    	$limit = 10;
    	$page = empty(I("post.p"))?1:I("post.p");
    	$start = ($page-1)*$limit;
    	$lists = M('station')->order("id desc")->limit($start,$limit)->select();
    	//print_r($lists);
    	if($lists){
    		$orderLogic = new OrderLogic();  
    		foreach($lists as $key=>$val){
    		    $num = 0;
    		    $adds = $orderLogic->getAddressName($val['province'],$val['city'],$val['district']);
    		    $lists[$key]['adds'] = $adds;
    		    $user_count = M('users')->where('station_id',$val['id'])->count();
    		    $lists[$key]['user_count'] = $user_count;
    		    $user_list = M('users')->where('station_id',$val['id'])->select();
    		    if($user_list){
    		    foreach($user_list as $k=>$v){
    		    	$extend_count = M('users')->where(array('station_leader'=>$v['user_id']))->count();
    		        if($extend_count>=30){
    		        	$num++;
    		        }
    		    }
    		    }
    		    $lists[$key]['user_extend_count'] =	$num;
    		}
    	}
    
        $count = M('station')->count();
        $Page  = new AjaxPage($count,$limit);
        $this->assign('pager',$Page->show());
    	$this->assign('lists',$lists);
    	return $this->fetch();
    }
    
    public function ajaxStationList(){
    	$where = ''; //搜索条件
    	$status = I('status/d');
    	$is_lock = I('is_lock/d');            
        $status !=='' && $where = "status=".$status;
        $is_lock !=='' && $where = "$where and is_lock=".$is_lock; 
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and name like '%$key_word%' or user_name like '%$key_word%')" ;
        }
        
        $limit = 10;
    	$page = empty(I("post.p"))?1:I("post.p");
    	$start = ($page-1)*$page;
        
        
        $lists = M('station')->order("id desc")->limit($start,$limit)->where($where)->select();
    	//print_r($lists);
    	if($lists){
    		$orderLogic = new OrderLogic();  
    		foreach($lists as $key=>$val){
    		    $adds = $orderLogic->getAddressName($val['province'],$val['city'],$val['district']);
    		    $lists[$key]['adds'] = $adds;
    		    $user_count = M('users')->where('station_id',$val['id'])->count();
    		    $lists[$key]['user_count'] = $user_count;
    		    $user_list = M('users')->where('station_id',$val['id'])->select();
    		    if($user_list){
    		    foreach($user_list as $k=>$v){
    		    	$extend_count = M('users')->where(array('station_leader'=>$v['user_id']))->count();
    		        if($extend_count>=30){
    		        	$num++;
    		        }
    		    }
    		    }	
    		}
    	}
        $count = M('station')->count();
        $Page  = new AjaxPage($count,$limit);
        $this->assign('pager',$Page->show());
    	$this->assign('lists',$lists);
        return $this->fetch();
    }
       
    //添加编辑品酒站
    public function addeditStation(){
    	
    	if(I('is_ajax') == 1 && IS_POST){
    		$data = I('post.');//收集数据

    		if($data){
    			if(empty($data['name'])){
    				echo json_encode(array('status'=>-1,'msg'=>'品酒站名称不能为空'));
    				exit;
    			}
    			if(empty($data['user_id'])){
    				echo json_encode(array('status'=>-1,'msg'=>'站长ID不能为空'));
    			    exit;
    			}
    		}
    		if($data['id']){
    			$id = $data['id'];
    		}
    		$data['addtime'] = time();
    	    if($id){
    	    	unset($data['id']);
    	    	$r = M('station')->where(array('id'=>$id))->save($data);
    	    	if($data['status'] == 1){
    	    		M('users')->where(array('user_id'=>$data['user_id']))->save(array('station_id'=>$id,'station_time'=>time(),'station_status'=>1));
    			    SendMessage(0,1,'您有一个俱乐部申请已通过审核，请到俱乐部管理中心查看！',array($data['user_id']),'俱乐部申请审核通过！');//通知站长
    			   // $ext_user_list = M('users')->where('first_leader'=>$data['user_id'])->getField('user_id');//邀请所有下线加入俱乐部
    			   // SendMessage(0,1,$data['name'].'邀请您加入他的品酒俱乐部，赶快去瞧瞧吧！',$ext_user_list,'品酒俱乐部邀请函！','');
				}
				elseif($data['status'] ==2){
					SendMessage(0,1,'您有一个俱乐部申请未通过审核，请到俱乐部管理中心查看！',array($data['user_id']),'俱乐部申请审核未通过！');
				}
    	    }
    	    else{
    	    	$data['addtime'] = time();
    	    	$repeat_name = M('station')->where(array('name'=>$data['name']))->find();
			    if($repeat_name){
			    	echo json_encode(array('status'=>-1,'msg'=>'站名重复，请重新填写！'));
				    exit;
			    }
    	        $r = M('station')->add($data);	
    	    }
    	    if($r){
    	    	$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/Station/stationList')),
                );
                $this->ajaxReturn($return_arr);
    	    }else{
    	    	$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => array('url' => U('admin/Station/addeditStation')),
                );
                $this->ajaxReturn($return_arr);
    	    }
    	}
    	$id = I('id/d');
    	if($id){
    		$stationInfo = M('station')->where(array('id'=>$id))->find();
    	    if(!$stationInfo){
    	    	$this->error('该品酒站不存在！');
    	    }
    	}
        $province = M('region')->where(array('parent_id'=>0))->select();
		$city =  M('region')->where(array('parent_id'=>$stationInfo['province']))->select();
		$area =  M('region')->where(array('parent_id'=>$stationInfo['city']))->select();
		$this->assign('province',$province);
		$this->assign('city',$city);
		$this->assign('area',$area);
        $this->assign('stationInfo', $stationInfo);
    	return $this->fetch();
    }
    
    //删除品酒站
    public function delstation(){
    	$id = I('id/d');
    	//是否存在订单
    	$r = M('station')->where(array('id'=>$id))->delete();
        M('users')->where(array('station_id'=>$id))->save(array('station_id'=>NULL,'station_time'=>NULL,'station_status'=>NULL));
		if(IS_POST){
		    if($r){
				$return_arr = array(
	                'status' => 1,
	                'msg' => '操作成功',
	                'data' => array('url' => U('admin/Exchange/goodsManage')),
	            );
	            $this->ajaxReturn($return_arr);
			}
			else{
				$return_arr = array(
	                'status' => -1,
	                'msg' => '删除失败',
	                'data' => array('url' => U('admin/Exchange/goodsManage')),
	            );
	            $this->ajaxReturn($return_arr);
			}	
		}else{
			if($r){
				$this->success('删除成功！');
			}else{
				$this->error('删除失败！');
			}
		}
    }
    
    
    /*
     * 品酒站站内成员列表
     * */
    public function stationMember(){
    	$limit = 10;
    	$page = empty(I("p/d"))?1:I("p/d");
    	$start = ($page-1)*$limit;
    	$station_id = empty(I("post.id"))?fasle:I("post.id");
    	$where['station_id'] = $station_id;
    	$lists = M('users')->order("user_id desc")->where($where)->limit($start,$limit)->select();
    	//print_r($lists);
    	if($lists){
            foreach($lists as $key=>$val){
            	$ext_num = M('users')->where(array('station_leader'=>$val['user_id']))->count();
            	$lists[$key]['ext_num'] = $ext_num;
            }
    	}
        $stationInfo = M('station')->where(array('id'=>$station_id))->find();
        $this->assign('stationInfo',$stationInfo);
        $count = M('users')->where($where)->count();
        $Page  = new AjaxPage($count,$limit);
        $this->assign('pager',$Page->show());
    	$this->assign('lists',$lists);
    	return $this->fetch();
    }
    
    
    //添加俱乐部成员
    public function addeditMember(){
    	
    	if(I('is_ajax') == 1 && IS_POST){
    		$data = I('post.');//收集数据

    		if($data){
    			if(empty($data['user_id'])){
    				echo json_encode(array('status'=>-1,'msg'=>'成员ID不能为空'));
    				exit;
    			}
    			else{
    				$is_in = M('users')->where(array('user_id'=>$data['user_id']))->getField('station_id');
    				if($is_in && !$data['is_update']){    					
    					$st_name = M('station')->where(array('id'=>$is_in))->getField('name');
    					echo json_encode(array('status'=>-1,'msg'=>'该成员已经加入'.$st_name));
    			        exit;
    				}
    			}
    			if(empty($data['station_id'])){
    				echo json_encode(array('status'=>-1,'msg'=>'俱乐部ID不能为空'));
    			    exit;
    			}
    		}
    		//更新入站日志
    		$station_action = M('users')->where(array('user_id'=>$data['user_id']))->getField('station_action');
    	    if($station_action){
    	    	$act_info = array('act_time'=>time(),
    	    	                  'station_id'=>(int)$data['station_id'],
    	    	                  'type'=>0,
    	    	                  'act_name'=>'加入品酒俱乐部');//type=0则为系统管理员操作，type=1则为用户自己操作
    	    	$station_action =  json_decode($station_action,true);
    	    	array_push($station_action,$act_info);
    	    	$station_action = json_encode($station_action);
    	    }
    	    else{
    	    	$act_info[] = array('act_time'=>time(),
    	    	                  'station_id'=>(int)$data['station_id'],
    	    	                  'type'=>0,
    	    	                  'act_name'=>'加入品酒俱乐部');//type=0则为系统管理员操作，type=1则为用户自己操作
    	    	$station_action =  json_encode($act_info,true);
    	    }
    	    $r = M('users')->where(array('user_id'=>$data['user_id']))->save(array('station_id'=>$data['station_id'],'station_status'=>$data['station_status'],'station_time'=>time(),'station_action'=>$station_action));
    	    if($r){
    	    	$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/Station/stationList')),
                );
                $this->ajaxReturn($return_arr);
    	    }else{
    	    	$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => array('url' => U('admin/Station/addeditStation')),
                );
                $this->ajaxReturn($return_arr);
    	    }
    	}
    	$id = I('id/d');
    	if($id){
    		$stationInfo = M('station')->where(array('id'=>$id))->find();
    	    if(!$stationInfo){
    	    	$this->error('该品酒站不存在！');
    	    }
    	}
    	$user_id = I('user_id/d');
    	$user = '';
    	if($user_id){
    		$user = M('users')->where(array('user_id'=>$user_id))->find();
    	}
    	$this->assign('user',$user);
        $this->assign('stationInfo', $stationInfo);
    	return $this->fetch();
    }
    
    
    /*
     * 俱乐部站内成员列表
     * */
    public function delMember(){
    	$user_id = I('user_id/d');
    	$id = I('id/d');
    	if(!$id||!$user_id){
    		$return_arr = array(
                'status' => -1,
                'msg' => '参数错误，请勿非法操作！',
                'data' => array('url' => U('admin/Station/stationMember',array('id'=>$id))),
            );
            $this->ajaxReturn($return_arr);
    	}
    	//更新入站日志
		$station_action = M('users')->where(array('user_id'=>$user_id))->getField('station_action');
	    if($station_action){
	    	$act_info = array('act_time'=>time(),
	    	                  'station_id'=>$id,
	    	                  'type'=>0,
	    	                  'act_name'=>'退出品酒俱乐部');//type=0则为系统管理员操作，type=1则为用户自己操作
	    	$station_action =  json_decode($station_action,true);
	    	array_push($station_action,$act_info);
	    	$station_action = json_encode($station_action);
	    }
	    else{
	    	$act_info[] = array('act_time'=>time(),
	    	                  'station_id'=>$id,
	    	                  'type'=>0,
	    	                  'act_name'=>'退出品酒俱乐部');//type=0则为系统管理员操作，type=1则为用户自己操作
	    	$station_action =  json_encode($act_info,true);
	    }
    	$r = M('users')->where(array('user_id'=>$user_id,'station_id'=>$id))->save(array('station_id'=>NULL,'station_status'=>0,'station_leader'=>0,'station_action'=>$station_action));
	    if($r){
	    	$name = M('station')->where(array('id'=>$id))->getField('name');
	    	SendMessage(0,1,'您已被移除当前俱乐部！当前俱乐部名称：'.$name,array($user_id),'移除俱乐部通知!');
			$return_arr = array(
                'status' => 1,
                'msg' => '操作成功',
                'data' => array('url' => U('admin/Station/stationMember',array('id'=>$id))),
            );
            $this->ajaxReturn($return_arr);
		}
		else{
			$return_arr = array(
                'status' => -1,
                'msg' => '移除失败',
                'data' => array('url' => U('admin/Station/stationMember',array('id'=>$id))),
            );
            $this->ajaxReturn($return_arr);
		}	
		
    }
    
    
    
    /*
     * 品酒会申请列表
     */
    public function applyList(){
    	$limit = 10;
    	$page = empty(I("post.p"))?1:I("post.p");
    	$start = ($page-1)*$limit;
    	$lists = M('station_party')->order("id desc")->limit($start,$limit)->select();
    	//print_r($lists);
    	if($lists){
    		$orderLogic = new OrderLogic();  
    		foreach($lists as $key=>$val){
    		    $adds = $orderLogic->getAddressName($val['province'],$val['city'],$val['district']);
    		    $lists[$key]['adds'] = $adds;
                $lists[$key]['station'] = M('station')->where(array('id'=>$val['station_id']))->find();	
    		    $lists[$key]['num_count'] = M('station_party_user')->where(array('party_id'=>$val['id']))->count();
    		}
    	}
    
        $count = M('station_party')->count();
        $Page  = new AjaxPage($count,$limit);
        $this->assign('pager',$Page->show());
    	$this->assign('lists',$lists);
    	return $this->fetch();
    }
    
    
    public function ajaxApplyList(){
    	$where = ''; //搜索条件
    	$status = I('status/d');          
        $status !=='' && $where = "status=".$status;
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and user_id = $key_word";
        }
        
        $limit = 10;
    	$page = empty(I("post.p"))?1:I("post.p");
    	$start = ($page-1)*$page;
        
        
        $lists = M('station_party')->order("id desc")->limit($start,$limit)->where($where)->select();
    	//print_r($lists);
    	if($lists){
    		$orderLogic = new OrderLogic();  
    		foreach($lists as $key=>$val){
    		    $adds = $orderLogic->getAddressName($val['province'],$val['city'],$val['district']);
    		    $lists[$key]['adds'] = $adds;
    		    $lists[$key]['station'] = M('station')->where(array('id'=>$val['station_id']))->find();	
    		    $lists[$key]['num_count'] = M('station_party_user')->where(array('party_id'=>$val['id']))->count();
    		}
    	}
        $count = M('station_party')->count();
        $Page  = new AjaxPage($count,$limit);
        $this->assign('pager',$Page->show());
    	$this->assign('lists',$lists);
        return $this->fetch();
    }
    
    
    /*
     * 品酒会详细信息
     */
    public function addeditApply(){

    	if(IS_POST){
    		$pdata = I('post.');
    		$id = I('post.id/d');
    		if(!$id){
    			$return_arr = array(
                    'status' => -1,
                    'msg' => '参数错误，请不要非法操作！',
                    'data' => array('url' => U('admin/Station/applyList')),
                );
                $this->ajaxReturn($return_arr);
    		}
    		$status = empty($pdata['status'])?0:$pdata['status'];
    		$r = M('station_party')->where(array('id'=>$id))->save(array('status'=>$status));
    		if($r){
    			$applyInfo = M('station_party')->where(array('id'=>$id))->find();
    			if($status == 1){
    			    SendMessage(0,1,'您有一个品酒会申请已通过审核，请到品酒会记录页面查看！',array($applyInfo['user_id']),'品酒会申请审核通过！');
				}
				elseif($status ==2){
					SendMessage(0,1,'您有一个品酒会申请未通过审核，请到品酒会记录页面查看！',array($applyInfo['user_id']),'品酒会申请审核未通过！');
				}
				$return_arr = array(
	                'status' => 1,
	                'msg' => '操作成功',
	                'data' => array('url' => U('admin/Station/addeditApply',array('id'=>$id))),
	            );
	            $this->ajaxReturn($return_arr);
			}
			else{
				$return_arr = array(
	                'status' => -1,
	                'msg' => '操作失败',
	                'data' => array('url' => U('admin/Station/addeditApply',array('id'=>$id))),
	            );
	            $this->ajaxReturn($return_arr);
			}	
    	}
    	
    	$id = I('id/d');
    	if(!$id){
    		$this->error('该品酒会不存在！');
    	}
    	
    	$applyInfo = M('station_party')->where(array('id'=>$id))->find();
    	if($applyInfo){
    		$applyInfo['station'] = M('station')->where(array('id'=>$applyInfo['station_id']))->find();
    		$orderLogic = new OrderLogic();  
    		$adds = $orderLogic->getAddressName($applyInfo['province'],$applyInfo['city'],$applyInfo['district']);
    		$applyInfo['adds'] = $adds.$applyInfo['address'];
    		$applyInfo['num_count'] = M('station_party_user')->where(array('party_id'=>$applyInfo['id']))->count();
    	}
    	
    	
    	$this->assign('applyInfo',$applyInfo);
    	return $this->fetch();
    }
    
    
    /*
     * 删除品酒会
     * */
    public function delApply(){
    	$id = I('id/d');
    	$r = M('station_party')->where(array('id'=>$id))->delete();
	    if($r){
			$return_arr = array(
                'status' => 1,
                'msg' => '操作成功',
                'data' => array('url' => U('admin/Station/applyList')),
            );
            $this->ajaxReturn($return_arr);
		}
		else{
			$return_arr = array(
                'status' => -1,
                'msg' => '移除失败',
                'data' => array('url' => U('admin/Station/applyList')),
            );
            $this->ajaxReturn($return_arr);
		}	
		
    }
    
    
    /*
     * 品酒会申请人员列表
     * */
    public function applyMember(){
    	$limit = 10;
    	$page = empty(I("p/d"))?1:I("p/d");
    	$start = ($page-1)*$limit;
    	$party_id = empty(I("post.id"))?fasle:I("post.id");
    	$where['party_id'] = $party_id;
    	$lists = M('station_party_user')->order("addtime desc")->where($where)->limit($start,$limit)->select();
    	if($party_id){
            $partyInfo = M('station_party')->where(array('id'=>$party_id))->find();
        }
        $this->assign('partyInfo',$partyInfo);
        $count = M('station_party_user')->where($where)->count();
        $Page  = new AjaxPage($count,$limit);
        $this->assign('pager',$Page->show());
    	$this->assign('lists',$lists);
    	return $this->fetch();
    }
    
    /*
     * 新增修改酒品会申请人员
     */
    public function addeditApplyMember(){
    	
    	if(I('is_ajax') == 1 && IS_POST){
    		$data = I('post.');//收集数据
    		if($data){
    			if(!empty($data['id'])){
    				$r = M('station_party_user')->where(array('id'=>$data['id']))->save(array('status'=>$data['status']));
    			}
    			else{
    				unset($data['id']);
    				$data['addtime'] = time();
    				$r = M('station_party_user')->add($data);
    			}
    		}
    	    if($r){
    	    	$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/Station/applyList',array('id'=>$data['id']))),
                );
                $this->ajaxReturn($return_arr);
    	    }else{
    	    	$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => array('url' => U('admin/Station/applyList')),
                );
                $this->ajaxReturn($return_arr);
    	    }
    	}
    	$id = I('id/d');
    	$party_id = I('party_id/d');
        $info = M('station_party_user')->where(array('id'=>$id))->find();

    	$this->assign('info',$info);
    	$this->assign('party_id',$party_id);
    	return $this->fetch();
    }
    
    
    /*
     * 删除品酒会申请成员
     * */
    public function delApplyMember(){
    	$id = I('id/d');
    	$r = M('station_party_user')->where(array('id'=>$id))->delete();
	    if($r){
			$return_arr = array(
                'status' => 1,
                'msg' => '操作成功',
                'data' => array('url' => U('admin/Station/applyList')),
            );
            $this->ajaxReturn($return_arr);
		}
		else{
			$return_arr = array(
                'status' => -1,
                'msg' => '移除失败',
                'data' => array('url' => U('admin/Station/applyList')),
            );
            $this->ajaxReturn($return_arr);
		}	
		
    }
    
    
    /*
     * 俱乐部经费申请列表
     * */
    public function fundApply(){
    	$limit = 10;
    	$page = empty(I("p/d"))?1:I("p/d");
    	$start = ($page-1)*$limit;
    	$where = 'id > 0';
    	$station_id = empty(I("post.station_id"))?0:I("post.station_id");
    	if(!empty($station_id)){
    		$where .= " and station_id = {$station_id}";
    	}
    	$lists = M('station_fund_apply')->order("add_time desc")->where($where)->limit($start,$limit)->select();
        $count = M('station_fund_apply')->where($where)->count();
        foreach($lists as $key=>$val){
        	$stationInfo = M('station')->where("id={$val['station_id']}")->find();
            $lists[$key]['stationInfo'] = $stationInfo;
        }

        $Page  = new AjaxPage($count,$limit);
        $this->assign('pager',$Page->show());
    	$this->assign('lists',$lists);
    	return $this->fetch();
    }
    
    
    /*
     * 俱乐部经费修改
     * */
    public function editFundApply(){
    	$id = I('id/d');
    	if(!$id){
    		$this->error('参数错误！');
    	}
    	if(IS_POST){
    		$arr = I('post.');
    		$data['status'] = $arr['status'];
    		$data['refusal_resaon'] = $arr['refusal_resaon'];
    		$r = M('station_fund_apply')->where(array('id'=>$id))->save($data);
    		if($r){
				$return_arr = array(
	                'status' => 1,
	                'msg' => '操作成功',
	                'data' => array('url' => U('admin/Station/editFundApply',array('id'=>$id))),
	            );
	            $this->ajaxReturn($return_arr);
			}
			else{
				$return_arr = array(
	                'status' => -1,
	                'msg' => '移除失败',
	                'data' => array('url' => U('admin/Station/editFundApply',array('id'=>$id))),
	            );
	            $this->ajaxReturn($return_arr);
			}	
    	}
    	$fundInfo = M('station_fund_apply')->where(array('id'=>$id))->find();
    	if($fundInfo){
    		$station = M('station')->where(array('id'=>$fundInfo['station_id']))->find();
    		$fundInfo['station'] = $station;
    		$user = M('users')->where(array('user_id'=>$station['user_id']))->find();
    		$fundInfo['user'] = $user;
    	}
    	$this->assign('fundInfo',$fundInfo);
    	return $this->fetch();
    }
    
    
}